import settings from '@/settings'

/**
 * 自定义时间格式化
 * @param any time 
 * @param string reg 
 */
 export const formatTime = (time, reg) => {
  if (!time) return '-'
  const date = typeof time === 'string' ? new Date(time.replace(/-/g, '/')) : time
  const map = {}
  map.yyyy = date.getFullYear()
  map.yy = ('' + map.yyyy).substr(2)
  map.M = date.getMonth() + 1
  map.MM = formatNumber(map.M)
  map.d = date.getDate()
  map.dd = formatNumber(map.d)
  map.H = date.getHours()
  map.HH = formatNumber(map.H)
  map.m = date.getMinutes()
  map.mm = formatNumber(map.m)
  map.s = date.getSeconds()
  map.ss = formatNumber(map.s)
  return reg.replace(/\byyyy|yy|MM|M|dd|d|HH|H|mm|m|ss|s\b/g, $1 => map[$1])
}

/**
 * 个数补零
 * @param number num 
 */
 export const formatNumber = (num) => {
  num = num + ''
  return num[1] ? num : `0${num}`
}

/**
 * 数组去重
 * @param {*} arr 
 */
export const uniqueArray = (arr) => {
  if (Array.hasOwnProperty('from')) {
    return Array.from(new Set(arr));
  } else {
    var n = {}, r = [];
    for (var i = 0; i < arr.length; i++) {
      if (!n[arr[i]]) {
        n[arr[i]] = true;
        r.push(arr[i]);
      }
    }
    return r;
  }
}

/**
 * 睡眠
 * @param {*} ms 延迟毫秒 
 */
 export const sleep = (ms = 2000) => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
  })
}

/**
 * 页面标题
 * @param {*} pageTitle 
 */
 export const getPageTitle = (pageTitle) => {
  if (pageTitle) {
    return `${pageTitle} - ${settings.title}`
  }
  return settings.title
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
 export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
 export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 * 
 * @param {*} int 
 * @returns 
 */
export const int2Bool = int => Boolean(Number(int))

/**
 * 是否是超管
 * @param {*} val 
 * @returns 
 */
export const isSuper = val => Number(val) == 1